<template>
  <div class="hello">
    <!-- form card -->
    <el-card
      v-for="(e, i) in dataModel"
      :key="e.index"
      :class="e.formStyle || 'box-card'"
    >
      <div slot="header" class="clearfix">
        <span>{{ e.formName }}</span>
      </div>
      <el-form
        :inline="true"
        :ref="dataModel[i].formRef"
        :model="dataModel[i]['formModel']"
        class="demo-form-inline"
      >
        <el-col :span="24">
          <el-col
            v-for="item in e.formComponent"
            :key="item.model"
            :span="item.type == 'upload' ? 24 : 5"
          >
            <el-form-item
              label-width="120px"
              :prop="item.model"
              :rules="item.rules"
              :label="item.label"
              class="postInfo-container-item"
            >
              <!-- input-->
              <el-input
                v-if="item.type == 'input'"
                v-model="dataModel[i]['formModel'][item.model]"
                style="width: 150px"
                class="filter-item"
                @keyup.enter.native="item.keyUpEnter"
              />
              <!-- select-->
              <el-select
                v-if="item.type == 'select'"
                v-model="dataModel[i]['formModel'][item.model]"
                :placeholder="item.placeholder || ''"
                clearable
                style="width: 150px"
                class="filter-item"
              >
                <el-option
                  v-for="e in item.options"
                  :key="e.value"
                  :label="e.lable"
                  :value="e.value"
                />
              </el-select>
              <!--cascader -->
              <el-cascader
                v-if="item.type === 'cascader'"
                v-model="dataModel[i]['formModel'][item.model]"
                :options="item.options"
                :props="{ emitPath: false, checkStrictly: true }"
                clearable
                style="width: 150px"
                class="filter-item"
              >
              </el-cascader>
              <!-- datepicker-->
              <el-date-picker
                v-if="item.type == 'datePicker'"
                v-model="dataModel[i]['formModel'][item.model]"
                style="width: 150px"
              />
              <!-- dateRangepicker -->
              <el-date-picker
                v-if="item.type == 'dateRangepicker'"
                v-model="dataModel[i]['formModel'][item.model]"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
              <el-upload
                :ref="item.model"
                v-if="item.type == 'upload'"
                class="upload-demo"
                v-model="dataModel[i]['formModel'][item.model]"
                :multiple="true"
                action="/minio/minio/upload"
                :headers="headers"
                :file-list="fileList[item.model]"
                :on-success="
                  (a, b, c) => uploadFileSuccess(a, b, c, item.model)
                "
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-col>
      </el-form>
    </el-card>
    <!-- 提交 -->
    <el-row class="edit-form-button" type="flex" justify="center">
      <el-button type="primary" @click="enterForm">提交审批</el-button>
      <el-button @click="cancelForm">取消</el-button>
    </el-row>
  </div>
</template>

<script>
import Cookies from "js-cookie";
const Auth = Cookies.get("Admin-Token");
export default {
  mounted() {
    console.log(this, "111");
  },
  props: ["dataModel", "submitHandle"],
  data() {
    return {
      // dataModel: this.dataModel.formComponent,
      // listQuery: this.dataModel.formComponent,
      formRules: this.dataModel.formRules,
      downloadLoading: false,
      fileList: {
        drawPath: [],
        archives: []
      },
      headers: { Authorization: "Bearer " + Auth }
      //  dataModel:[{
      //    formRef:'formFirst',//表单ref
      //    formModel:this.dataModel.formModel,//表单model
      //   formComponent:this.dataModel.formComponent,
      //    formName:'表单A'//表单标题
      //   },{
      //   formRef:'formSecond',
      //    formModel:this.dataModel.formModel,
      //     formComponent:this.dataModel.formComponent,
      //    formName:'表单B'
      //   },{
      //     formRef:'formThird',
      //    formModel:this.dataModel.formModel,
      //     formComponent:this.dataModel.formComponent,
      //    formName:'表单C'
      //   }],
    };
  },
  created() {
    console.log(this.dataModel);
    this.fileList.drawPath =
      [{ name: "设备主图", url: this.dataModel[0]["formModel"]["drawPath"] }] ||
      [];
    this.dataModel[2]["formModel"]["archives"].forEach(function(e) {
      e.url = e.viewPath;
      e.name = e.archiveName;
    });
    this.fileList.archives = this.dataModel[2]["formModel"]["archives"] || [];
  },
  methods: {
    uploadFileSuccess(res, file, fileList, type) {
      console.log(fileList, "fileList");
      //把fileList组装成后端需要的数据,这里根据透传的type来区分2个上传
      if (type == "drawPath") {
        //设备主图 只有一张

        this.dataModel[0].formModel.drawPath = file.response.data.viewPath;
      } else {
        //档案设备
        const data = [];
        fileList.map(item => {
          data.push({
            archivePath: item.response.data.viewPath,
            viewPath: item.response.data.viewPath,
            archiveName: item.name
          });
        });
        this.dataModel[2].formModel.archives = data;
      }

      console.log(this.dataModel);
    },
    cancelForm() {
      this.$store.dispatch("tagsView/delVisitedView", {
        path: this.$route.fullPath
      });
      this.$router.push("/device-basic/index");
    },
    enterForm() {
      //动态表单提交
      let arrForm = []; //哪些表单需要做校验
      let arrModel = []; //表单的值
      let newArr = []; //承接promise的返回结果
      let _self = this;
      this.dataModel.forEach((item, index) => {
        //将有权限的表单做校验等等
        console.log("+++", item.formRef);

        checkForm(item.formRef); //校验
        arrModel.push(item); //需要校验的表单的值
      });
      function checkForm(arrName) {
        //根据form表单的ref，动态生成promise，再对其坐表单校验，都通过了再去做处理
        console.log(_self.$refs[arrName], "-----");
        var result = new Promise(function(resolve, reject) {
          _self.$refs[arrName][0].validate(valid => {
            if (valid) {
              resolve();
            } else {
              reject();
            }
          });
        });
        newArr.push(result); //push 得到promise的结果
      }
      Promise.all(newArr)
        .then(function() {
          //都通过了
          console.log(arrModel);
          console.log("恭喜，表单全部验证通过");

          _self.submitHandle(arrModel);
        })
        .catch(function() {
          console.log("表单验证失败");
         // _self.submitHandle(arrModel);
          console.log("err");
        });
    }
  }
};
</script>

<style scoped>
.box-card {
  border: 0px;
  background-color: #fff;
  overflow: hidden;
  color: #303133;
  box-shadow: 0 0px 0px 0 rgba(0, 0, 0, 0.1);
}
.box-margin-card {
  margin-top: 20px;
  border: 0px;
  background-color: #fff;
  overflow: hidden;
  color: #303133;
  box-shadow: 0 0px 0px 0 rgba(0, 0, 0, 0.1);
}
.edit-form-button {
  margin: 20px 0;
}
</style>
